#include <stdlib.h>
#include "user.h"

user_data * emptyuser = NULL;
user_data * emptyuserend = NULL;
int emptylen = 0;
user_data * logonuser = NULL;
user_data * logonuserend = NULL;
int logonlen = 0;

void init_userlist()
{
	return;
	if(emptyuser!= NULL)
		return;
	//emptyuser = calloc(CALLOC_LEN, sizeof(user_data));
	//printf("fd=%d uid=%d name=%s\n", userlist->fd, userlist->uid, userlist->name);
	//bzero(userlist, CALLOC_LEN * sizeof(user_data));
	//printf("fd=%d uid=%d name=%s\n", userlist->fd, userlist->uid, userlist->name);
}

void add_emptyuser(user_data * user)
{
	if(emptyuser == NULL)
	{
		emptyuser = user;
		emptyuserend = user;
	}
	else 
	{
		emptyuserend->next = user;
		user->prev = emptyuserend;
		emptyuserend = user;
	}
	emptylen += 1;
	//return user;
}

void add_logonuser(user_data * user)
{
	if(logonuser == NULL)
	{
		logonuser = user;
		logonuserend = user;
	}
	else
	{
		logonuserend->next = user;
		user->prev = logonuserend;
		logonuserend = user;
	}
	logonlen += 1;
}

user_data * get_empty_user()
{
	user_data * user = calloc(1, sizeof(user_data));
	add_emptyuser(user);
	return user;
}

user_data * take_emptyuser_by_fd(int fd)
{
	user_data * tmpuser = emptyuser;
	while(tmpuser != NULL)
	{
		if(tmpuser->fd == fd)
		{
			if(tmpuser->prev != NULL)
			{
				tmpuser->prev->next = tmpuser->next;
			}
			if(tmpuser->next != NULL)
			{
				tmpuser->next->prev = tmpuser->prev;
			}
			return tmpuser;
		}
	}
	return NULL;
}


int user_log_on(int fd, char * name)
{
	user_data * user = take_emptyuser_by_fd(fd);
	if(strlen(name) >= MAX_NAME_LEN )
	{
		printf("name :%s too long! fd=%d", name, fd);
		free(user);
		return -1;
	}
	strcpy(&(user->name), name);
	add_logonuser(user);
}
